package com.kgc.web;

import com.kgc.dao.AdminDao;
import com.kgc.entity.Admin;
import com.kgc.untils.CodecUtils;
import com.kgc.vo.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AdminLoginServlet", value = "/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String opt = request.getParameter("opt");
        HttpSession session = request.getSession();
        PrintWriter writer = response.getWriter();
        AdminDao adminDao = new AdminDao();

        //验证码
        if ("captcha".equals(opt)) {
            String code = (String) session.getAttribute("code");
            String captcha = request.getParameter("captcha");
            if (code.equalsIgnoreCase(captcha)) {
                writer.write(R.success("验证成功!").toJSON());
            } else {
                writer.write(R.error("验证码有误!").toJSON());
            }
            //登录
        } else if ("login".equals(opt)) {
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            Admin admin = adminDao.selectAdminByEmail(email);
            if (admin != null) {
                String salt = admin.getSalt();
                if (CodecUtils.match(admin.getPassword(), password, salt)) {
                    session.setAttribute("admin", admin);
                    writer.write(R.success("登录成功!").toJSON());
                } else {
                    writer.write(R.error("登陆失败,密码有误!").toJSON());
                }
            } else {
                writer.write(R.error("登录失败,用户名或者邮箱不存在!").toJSON());
            }
            //管理员退出登录
        } else if ("exit".equals(opt)) {
            session.invalidate();
            response.sendRedirect("/page/admin/login.jsp");
            //管理员首页数据统计
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
